package hot100.普通数组;

/**
 * 给定一个整数数组 nums，将数组中的元素向右轮转 k 个位置，其中 k 是非负数。
 *
 * @ https://leetcode.cn/problems/rotate-array/description/?envType=study-plan-v2&envId=top-100-liked
 * @date 2025/08/27
 */
public class 轮转数组_189 {

    public static void main(String[] args) {

        轮转数组_189 impl = new 轮转数组_189();

        impl.rotate(new int[]{1, 2}, 7);

    }

    /**
     * 找规律
     * 1,2,3,4,5,6,7 -> 5,6,7,1,2,3,4    k =3
     * <p>
     * 先将原数组反转
     * 1,2,3,4,5,6,7 -> 7,6,5,4,3,2,1
     * 然后将前 k 个数字反转，将后面 n - k 个数字反转
     */
    public void rotate(int[] nums, int k) {
        k %= nums.length;

        replace(nums, 0, nums.length - 1);
        replace(nums, 0, k - 1);
        replace(nums, k, nums.length - 1);
    }

    private void replace(int[] nums, int left, int right) {
        while (left < right) {
            int leftNum = nums[left];
            nums[left] = nums[right];
            nums[right] = leftNum;
            left++;
            right--;
        }
    }

}
